package cate.game.role.farm;

import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import easy.java.practice.errorcode.EcResult;
import org.springframework.data.annotation.Transient;

@NoteClass("基于时间添加的挑战次数")
public class TimeBasedPlayTimes {
    @NoteField("当前次数")
    public int current;
    @NoteField("上次检测时间")
    public long lastCheckTime;

    @Transient
    @NoteField("最大值")
    public int max;
    @Transient
    @NoteField("间隔")
    private long interval;
    @Transient
    @NoteField("是否设置完毕")
    private boolean ready;

    public TimeBasedPlayTimes() {
        current = 0;
        lastCheckTime = System.currentTimeMillis();
    }

    public TimeBasedPlayTimes(int initTimes) {
        current = initTimes;
        lastCheckTime = System.currentTimeMillis();
    }

    /**
     * 设置常量
     *
     * @param max      最大值
     * @param interval 间隔
     */
    public void setup(int max, long interval) {
        this.max = max;
        this.interval = interval;
        ready = true;
        if (current > max) {
            current = max;
        }
        if (current == max) {
            lastCheckTime = 0;
        }
    }

    /**
     * 循环
     */
    public void tick() {
        if (!ready) {
            return;
        }
        if (current >= max) {
            return;
        }
        long nowTime = System.currentTimeMillis();
        for (int i = current; i < max; i++) {
            if (nowTime >= lastCheckTime + interval) {
                current++;
                if (current == max) {
                    lastCheckTime = 0;
                    break;
                } else {
                    lastCheckTime += interval;
                }
            } else {
                break;
            }
        }
    }

    /**
     * 外部添加次数
     *
     * @param num 添加次数
     */
    public void addCurrent(int num) {
        current = Math.min(max, current + num);
        if (current == max) {
            lastCheckTime = 0;
        }
    }

    /**
     * 是否有可用次数
     *
     * @return 查询结果
     */
    public EcResult<Void> available() {
        EcResult<Void> r = new EcResult<>();
        if (current <= 0) {
            return r.fail("次数不足");
        }
        return r.success();
    }

    /**
     * 是否达到次数上限
     */
    public boolean max() {
        return current >= max;
    }

    /**
     * 使用次数
     *
     * @return 使用结果
     */
    @SuppressWarnings("UnusedReturnValue")
    public EcResult<Void> useCurrent() {
        EcResult<Void> r = new EcResult<>();
        if (current <= 0) {
            return r.fail("次数不足");
        }
        if (current == max) {
            lastCheckTime = System.currentTimeMillis();
        }
        current--;
        return r.success();
    }
}
